#include "Logger.h"

#include <ctime>
#include <iostream>

Logger_ &Logger_::GetInstance()
{
    static Logger_ logger;
    return logger;
}

Logger_::Logger_()
{
    // 创建专门的写日志线程，lambda表达式作为对象。
    std::thread writeLogTask([&]()
                             {
        for(;;)
        {
            time_t now=time(nullptr);
            struct tm* nowtm=localtime(&now);
            char file_naem[128];
            sprintf(file_naem,"%d-%d-%d-log.txt",nowtm->tm_year+1900, nowtm->tm_mon+1, nowtm->tm_mday);

            FILE* pf=fopen(file_naem, "a+");
            if(pf==nullptr)
            {
                std::cout<<"logger file: "<<file_naem<<" open error!"<<std::endl;
                exit(EXIT_FAILURE);
            }
            
            std::string msg=m_lckQue.pop();
            char msg_time[128] = {0};
            sprintf(msg_time,"[%02d:%02d:%02d]:", nowtm->tm_hour, nowtm->tm_min, nowtm->tm_sec);
            msg.insert(8,msg_time);
            msg += "\n";
            
            fputs(msg.c_str(), pf);
            fclose(pf);
        } });

    writeLogTask.detach(); // 分离线程
}

// 设置日志级别
void Logger_::SetLevel(Level level)
{
    m_loglevel = level;
}

// 写日志，我们调用的是这个，写入异步日志队列 TO PONDER
void Logger_::Log(std::string msg)
{
    m_lckQue.push(msg);
}
